package cn.skyquant.quant4j.service.boot.web.controller;

import cn.skyquant.quant4j.api.dto.ResultDTO;
import cn.skyquant.quant4j.api.fund.FundDTO;
import cn.skyquant.quant4j.api.order.OrderService;
import cn.skyquant.quant4j.sdk.util.time.CalendarUtils;
import cn.skyquant.quant4j.service.boot.model.fund.FundDaily;
import cn.skyquant.quant4j.service.boot.model.fund.FundService;
import cn.skyquant.quant4j.service.boot.web.annotation.NoVerify;
import com.google.common.collect.Lists;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/fund")
public class FundController {

    @Resource
    OrderService orderService;

    @Resource
    FundService fundService;

//    @RequestMapping(value = "/all", method = RequestMethod.GET)
//    @ResponseBody
//    @NoVerify
//    public ResultDTO<List> allFund() {
//        return ResultDTO.success(fundService.findAllFund());
//    }

    @RequestMapping(value = "/{days}", method = RequestMethod.GET)
    @ResponseBody
    @NoVerify
    public ResultDTO<Map> get(@PathVariable int days) {
        long time = System.currentTimeMillis();
        long begin = CalendarUtils.addDate(-days).getTime();
        Map<String,Object> resultMap = new HashMap<>();
        List<String> nameList = Lists.newArrayList();
        List<Map<String,Object>> listMap = Lists.newArrayList();
        resultMap.put("nameList",nameList);
        resultMap.put("dataList",listMap);
        List<FundDTO> fundDTOS = fundService.findAllFund();
        Set<String> dates = new HashSet<>();
        for(FundDTO fundDTO:fundDTOS){
            nameList.add(fundDTO.name);
            List<Object[]> list= new ArrayList<>();
            List<FundDaily> fundDTOList = fundService.findDaily(fundDTO.id, System.currentTimeMillis());
            fundDTOList.stream().filter(x->x.date.getTime()> begin && x.date.getTime()<time && x.basic != x.equity).forEach(x->{
                list.add(new Object[]{CalendarUtils.formatGMTSimple(x.date),x.equity/x.basic});
                dates.add(CalendarUtils.formatGMTSimple(x.date));
            });
            Map<String,Object> dv = new HashMap<>();
            dv.put("name",fundDTO.name);
            dv.put("data",list);
            listMap.add(dv);
        }
        List<String> dateList = dates.stream().sorted(Comparator.comparing(String::toString)).collect(Collectors.toList());
        resultMap.put("dates",dateList);
        return ResultDTO.success(resultMap);
    }
}
